﻿using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using IronOne.SalesOne.BusinessObjects;

namespace IronOne.SalesOne.SalesOneWeb.UserManagement
{
    public partial class AssignPermissions : SOSecurityPage
    {
        Facade.StructureFacade structureFacade = new Facade.StructureFacade();
        //private static int pageNo = 1;

        public int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]);

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SetCredentials(ValidateUserCredentials(Request.Url.LocalPath));

                btnSave.Visible = false;
                grdTasks.Visible = false;

                lblError.ForeColor = Color.Black;
                lblError.Text = "";

                if (!IsPostBack)
                {
                    PopulateRoles(structureFacade.GetAspnetUserRoles(""));

                    if (Page.Request.Params["RoleId"] != null)
                    {
                        ddlUserRole.SelectedValue = Page.Request.Params["RoleId"].ToString();
                        //txtPageNo.Text = "1";
                        Search();
                        grdTasks.Visible = true;
                    }
                }

            }
            catch { MassageSummery("IIS514"); }

        }

        public void PopulateRoles(List<UserRole_aspnet> userTypes)
        {
            ddlUserRole.DataSource = userTypes;
            ddlUserRole.DataTextField = "RoleName";
            ddlUserRole.DataValueField = "RoleId";
            ddlUserRole.DataBind();

            InsertDDLItems(ddlUserRole, "Select...", 0);
            
        }

        public void PopulateTasks(List<Task> tasks)
        {
            if (tasks.Count > 0)
            {              
                grdTasks.DataSource = tasks;
                grdTasks.DataBind();
                btnSave.Visible = true;
                grdTasks.Visible = true;

                /*if (tasks.Count < pageSize)
                {
                    btnNext.Visible = false;
                    if (txtPageNo.Text != "")
                    {
                        if (Convert.ToInt32(txtPageNo.Text) == 1)
                        {
                            txtPageNo.Visible = false;
                            btnGo.Visible = false;
                            btnPrevious.Visible = false;
                        }
                    }
                }*/
            }
            else
            {
                MassageSummery("IIS504");
                btnSave.Visible = false;
                grdTasks.Visible = false;

                /*btnNext.Visible = false;
                btnPrevious.Visible = false;
                btnGo.Visible = false;
                txtPageNo.Visible = false;*/
            }
           
        }

        public void InsertDDLItems(DropDownList ddl, string Text, int Position)
        {
            ListItem item = new ListItem(Text, Text);
            ddl.Items.Insert(Position, Text);
            //ddl.Items.Add( item);
        }

        protected void ddlUserRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //txtPageNo.Text = "1";
                Search();
            }
            catch { MassageSummery("IIS514"); } 
        }

        public void SetPermissionValues(string permissionString)
        {
           
            //if(permissionString.Contains("C"))//Create
            //    chkCreate.Checked=true;

            //if(permissionString.Contains("E"))//Enquiry
            //    chkEnquiry.Checked=true;

            //if(permissionString.Contains('D'))//delete
            //    chkDelete.Checked=true;

            //if(permissionString.Contains("U"))//update
            //    chkUpdate.Checked=true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                GetCheckedItems();
                grdTasks.Visible = true;
                btnSave.Visible = true;

                MassageSummery("IIS401");
            }
            catch
            {
                MassageSummery("IIS502");
            }  
        }

        protected void ddlTasks_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (ddlTasks.SelectedIndex > 0)
            //{
            //    string permissions = "";

            //    try
            //    {
            //        permissions = structureFacade.GetPermissions(new Guid(ddlUserRole.SelectedValue), Convert.ToInt32(ddlTasks.SelectedValue));
            //    }
            //    catch { permissions = ""; }

            //    if (permissions != null && permissions != "")
            //    {
            //        string[] arrPermissions = permissions.Split(new char[] { '=' });
            //        SetPermissionValues(arrPermissions[1]);
            //    }
            //}
        }

        protected void grdUsers_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //DataRowView rowView = (DataRowView)e.Row.DataItem;
                //sourceDocDS.sourceDocDataRow mainLineRow = (sourceDocDS.sourceDocDataRow)rowView.Row;
                Task task = (Task)e.Row.DataItem;
                CheckBox chkCreate = (CheckBox)e.Row.FindControl("chkCreate");
                CheckBox chkDelete = (CheckBox)e.Row.FindControl("chkDelete");
                CheckBox chkUpdate = (CheckBox)e.Row.FindControl("chkUpdate");
                CheckBox chkEnquiry = (CheckBox)e.Row.FindControl("chkEnquiry");
               

                string permissions = "";

                try
                {
                    permissions = structureFacade.GetPermissions(new Guid(ddlUserRole.SelectedValue), Convert.ToInt32(task.TaskId));
                }
                catch { permissions = ""; }

               
                if (permissions != null && permissions != "")
                {
                    string[] arrPermissions = permissions.Split(new char[] { '=' });
                    string permissionString = arrPermissions[1];

                    if (permissionString.Contains("c"))//Create
                        chkCreate.Checked = true;

                    if (permissionString.Contains("v"))//Enquiry
                        chkEnquiry.Checked = true;

                    if (permissionString.Contains('d'))//delete
                        chkDelete.Checked = true;

                    if (permissionString.Contains("u"))//update
                        chkUpdate.Checked = true;
                }

               

                //switch (mainLineRow.VismaStatus)
                //{
                //    case IVismaStatus.IN_ACTIVE: LblVismaStatus.Text = ""; break;
                //    case IVismaStatus.PENDING: LblVismaStatus.Text = "Pending"; break;
                //    case IVismaStatus.ACCEPTED: LblVismaStatus.Text = "Accepted "; break;
                //    case IVismaStatus.REJECTED: LblVismaStatus.Text = "Rejected"; break;
                //    default: LblVismaStatus.Text = ""; break;
                //}
            }
        }

        protected void grdUsers_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //int[] cols = (int[])Session["hideCols"];
            int[] cols = {4,6};
            if (cols != null)
            {
                for (int i = 0; i < cols.Length; i++)
                {
                    e.Row.Cells[cols[i]].Visible = false;

                }
            }


        }

        protected void grdUsers_OnDataBound(object sender, EventArgs e)
        {

            int rw = grdTasks.Rows.Count;
            if (rw > 0)
            {
                List<GridViewStyle> styleList = new List<GridViewStyle> {
                new GridViewStyle{
                    ColumnId = "TaskName",
                    ColumnHeader = "Task Name",
                    ColumnWidth = 150},
                
            };

                /*btnNext.Visible = true;
                if (txtPageNo.Text != "1")
                {
                    btnPrevious.Visible = true;
                }
                else
                {
                    btnPrevious.Visible = false;
                }
                btnGo.Visible = true;
                txtPageNo.Visible = true;*/


                TableCellCollection columns = grdTasks.HeaderRow.Cells;

                if (styleList != null)
                {
                    for (int i = 0; i < columns.Count; i++)
                    {
                        GridViewStyle style = styleList.SingleOrDefault(p => p.ColumnId.Contains(columns[i].Text));
                        if (style != null)
                        {
                            columns[i].Text = style.ColumnHeader;
                            columns[i].ControlStyle.Width = style.ColumnWidth;
                        }
                    }
                }
            }
            else
            {
                /*btnNext.Visible = false;
                btnPrevious.Visible = false;
                btnGo.Visible = false;
                txtPageNo.Visible = false;*/
            }
        }

        private void GetCheckedItems()
        {
            CheckBox chkCreate ;
            CheckBox chkDelete; 
            CheckBox chkUpdate ;
            CheckBox chkEnquiry ;

            string chkBoxIndex = string.Empty;

            //loop through each row in the GridView

            foreach (GridViewRow row in grdTasks.Rows)
            {
                Task task = (Task)row.DataItem;
                //get the index of the current CheckBox

                chkBoxIndex = row.Cells[5].Text;

                //chk = (CheckBox)row.FindControl(ctrl);
                chkCreate = (CheckBox)row.FindControl("chkCreate");
                chkDelete = (CheckBox)row.FindControl("chkDelete");
                chkUpdate = (CheckBox)row.FindControl("chkUpdate");
                chkEnquiry = (CheckBox)row.FindControl("chkEnquiry");

                //now see if the current CheckBox is checked

                StringBuilder sb = new StringBuilder();

                if (chkCreate.Checked)//create
                    sb.Append("c,");

                if (chkEnquiry.Checked)//enqiury
                    sb.Append("v,");

                if (chkDelete.Checked)//delete
                    sb.Append("d,");

                if (chkUpdate.Checked)//update
                    sb.Append("u,");

                if (sb.Length != 0)
                    sb.Remove(sb.Length - 1, 1).ToString();

                TaskCredentials taskCredentials = new TaskCredentials();
                taskCredentials.RoleId=new Guid(ddlUserRole.SelectedValue);
                taskCredentials.TaskId=Convert.ToInt16( row.Cells[4].Text);
                taskCredentials.Credentials=sb.ToString();

                try
                {
                    int result = structureFacade.UpdatePermission(taskCredentials);
                }
                catch(Exception ex)
                {
                    structureFacade.InsertPermission(taskCredentials);
                }

            }

        }

        public void SetCredentials(StringCollection credential)
        {
            foreach (string item in credential)
            {
                if (item.ToLower() == "u")
                    btnSave.Visible = true;     
            }
        }

        /*protected void btnPrevious_Click(object sender, EventArgs e)
        {
            try
            {
                if (pageNo != 1)
                {
                    pageNo = pageNo - 1;
                    txtPageNo.Text = pageNo.ToString();

                    Search(pageNo);
                }

            }
            catch { MassageSummery("IIS514"); }
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (pageNo != 1)
                {
                    pageNo = pageNo + 1;
                    txtPageNo.Text = pageNo.ToString();

                }
                else
                {
                    pageNo = 2;
                    txtPageNo.Text = "2";

                }

                Search(pageNo);
            }
            catch { MassageSummery("IIS514"); }
        }

        protected void txtGo_Click(object sender, EventArgs e)
        {
            try
            {
                int p = int.Parse(txtPageNo.Text);
                if (p != 0)
                {
                    try
                    {
                        Search(p);
                        pageNo = p;
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
            }
            catch { MassageSummery("IIS505"); }
        }*/

        public void Search()
        {
            if (ddlUserRole.SelectedIndex > 0)
                //PopulateTasks(structureFacade.GetTasksForRole(new Guid(ddlUserRole.SelectedValue)));
                PopulateTasks(structureFacade.GetTasks("TaskName ASC"));
            else
            {
                /*btnNext.Visible = false;
                btnPrevious.Visible = false;
                btnGo.Visible = false;
                txtPageNo.Visible = false;*/
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UserManagement/ViewRole.aspx");
        }
    }
}
